<template>
  <div>
    <!-- <FormTitle title="运价信息" /> -->
    <div>
      <VForm
        ref="formRef"
        :model="model"
        :rules="rules"
        :fieldList="fieldList"
        :options="formOption"
        :originOption="options"
      >
        <template #file="{ input, value }">
          <Upload
            label="运价文件"
            :require="flage"
            :modelValue="value"
            @update:modelValue="input"
          >
            <template #headRight>
              <el-button
                text
                type="primary"
                @click.stop="handleDownLoadTemplate"
              >
                <span>下载模板</span>
              </el-button>
              <el-button
                v-if="billingType"
                text
                type="primary"
                @click.stop="handleLook"
              >
                <span>预览</span>
              </el-button>
            </template>
          </Upload>
        </template>
        <template #currency="{ value, input }">
          <CurrencySelect
            @update:model-value="input"
            :model-value="value"
            :defaultCurrency="false"
          />
        </template>
        <template #discount="{ value, input }">
          <Discount :value="value" @input="input" />
        </template>
        <template #volumeWeight="{ value, input }">
          <VolumeWeight :options="options" :data="value" @input="input" />
        </template>
      </VForm>
    </div>
  </div>
</template>

<script setup lang="jsx">
import FormTitle from "@/components/Form/FormTitle.vue";
import VForm from "@/components/Form/index.vue";
import Upload from "@/components/Upload/index.vue";
import CurrencySelect from "@/components/CurrencySelect/index.vue";
import Discount from "./components/Discount/index.vue";
import VolumeWeight from "./components/VolumeWeight/index.vue";
const router = useRouter();
import { getImportUrl } from "@/api/public";

const props = defineProps({
  options: { type: Object, default: () => ({}) },
  throwingWeight: { type: Boolean, default: false },
  data: { type: Object, default: () => ({}) },
  billingType: { type: [String, Number], default: "" },
});

const formRef = ref();
const model = ref({
  is_registered: 0,
  is_volume: 1,
});
watch(
  () => props.billingType,
  () => {
    if (props?.data?.id) return;
    if (props.billingType == 4) {
      model.value.is_volume = 0;
    } else {
      model.value.is_volume = 1;
    }
  }
);
const fileList = ref([]);

const loading = ref(false);
const flage = ref(true);
watch(
  () => props.data,
  (val) => {
    if (val?.id) {
      rules.file[0].required = false;
      flage.value = false;
    }
    if (val.currency) {
      const {
        discount,
        currency,
        is_registered,
        inner_no_discount,
        is_volume,
        count_reason,
        volume_calc_type,
        ratio_type,
        ratio_value,
        fuel_rate,
      } = val || {};
      model.value = {
        discount: { discount, inner_no_discount: inner_no_discount },
        currency,
        is_registered,
        is_volume,
        volumeWeight: { volume_calc_type, ratio_type, ratio_value },
        count_reason,
        fuel_rate,
      };
    }
  }
);

const publicStyle = { style: { width: "360px" } };
const fieldList = [
  // { field: "file", slot: "file", full: true, style: { width: "400px" } },
  { type: "br" },
  {
    field: "discount",
    slot: "discount",
    label: "折扣",
  },
  {
    field: "currency",
    label: "币种",
    slot: "currency",
    ...publicStyle,
  },
  {
    field: "is_registered",
    label: "是否挂号",
    type: "radio",
    options: {
      data: [
        { label: "挂号", value: 1 },
        { label: "不挂号", value: 0 },
      ],
    },
    ...publicStyle,
  },
  { type: "br" },
  {
    field: "is_volume",
    label: "是否取体积重",
    type: "radio",
    originField: "is_volume",
    ...publicStyle,
    show: ({ model }) => props.billingType !== 4,
  },
  { type: "br" },
  {
    field: "volumeWeight",
    slot: "volumeWeight",
    style: { width: "100%" },
    show: ({ model }) => model.is_volume === 1 && props.throwingWeight,
  },
  {
    field: "count_reason",
    label: "抛重计重因子",
    default: `<div class='text-[12px] text-[#999] leading-[17px] ml-[8px]'>计算逻辑：长*宽*高/计算因子=公斤重抛重（kg）乘以1000=克，再来跟实重g（实际重量）对比，谁大取谁；</div>`,
    show: ({ model }) => model.is_volume === 1 && props.billingType !== 4,
  },
  { type: "br" },
  {
    field: "fuel_rate",
    label: "燃油费比率",
    append: "%",
  },
];

const rules = reactive({
  file: [{ required: true, message: "请上传运费文件", trigger: "blur" }],
  currency: [{ required: true, message: "请选择币种", trigger: "blur" }],
  count_reason: [
    { required: true, message: "请输入抛重计重因子", trigger: "blur" },
  ],
});

const formOption = {
  inline: true,
  labelPosition: "top",
};

const submit = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const formInfo = await formRef.value.submit();
      const { file, ...reset } = formInfo;
      resolve({ ...reset, file: file?.[0]?.response || [] });
    } catch (e) {
      console.warn(e);
      reject("freight");
    }
  });
};

const handleDownLoadTemplate = async () => {
  const { billingType } = props;
  const { data } =
    (await getImportUrl({ type: "channel.transportCost" })) || {};
  const _url = data?.[billingType].uri;
  if (_url) window.open(_url, "noopener", "noreferrer");
};

const handleLook = () => {
  router.push({
    path: `/logistics-settings/channel/transport-cost`,
    query: { id: props.data?.id },
  });
};

defineExpose({ submit });
</script>
